<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/6/4
 * Time: 12:51
 * 获取视频封面和时长
 */
require_once dirname(__DIR__)."/common.php";
use app\cls\tom\FFmpeg;
use app\lib\db\DbException;
use app\cls\tom\Queue;
use app\cls\tom\Tools;
use app\cls\tom\SysResource;
use app\cls\tom\Process;
use app\model\Video;

$process = new Process(__FILE__);
$process->setProcessNum(2);
$process->initProcess();

$redis = SysResource::getRedis();
$db =  SysResource::getDB(true);
$materialModel = new Video($db);
$userMaterialModel = new \app\model\UserMaterial($db);
$ffmpeg = new FFmpeg(false);
$queue = new Queue($redis,REDIS_PREFIX."ori_material_h");
$queueNum = $queue->getQueueNum();
try{
    while(true){
        for($i = 0 ;$i< $queueNum;$i++){
            for($j = 0 ;$j < 100;$j++){
                $dataStr = $queue->pop($i);
                if(empty($dataStr)){
                    break;
                }
                $data = @json_decode($dataStr,true);
                if(!is_array($data)){
                    continue;
                }
                print_r($data);
                $videoUrl = "";
                if($data["type"] == "ori"){
                    $info = $materialModel->getinfo(["id"=>$data["id"]]);
                    $videoUrl = $info["ori_video_url"];
                }else if($data["type"] == "user"){
                    $info = $userMaterialModel->getinfo(["id"=>$data["id"]]);
                    $videoUrl = $info["video_url"];
                }else{
                    continue;
                }
                $duration = $ffmpeg->getVideoLen($videoUrl);
                $image = CDN_PATH."/cover/".Tools::UUID().".jpg";
                $re = $ffmpeg->getCoverFromVideo($videoUrl,$image);
                if($re){
                    $up = ["time_length"=>$duration];
                    if(empty($info["pic"])){
                        $up["pic"] = str_replace(CDN_PATH,CDN_HOST,$image);
                    }
                    if($data["type"] == "ori"){
                        $materialModel->save("update",$up,["id"=>$data["id"]]);
                    }else if($data["type"] == "user"){
                        $userMaterialModel->save("update",$up,["id"=>$data["id"]]);
                    }
                }else{
                    Tools::writeLog(["key"=>"cover","msg"=>"封面截图失败","detail"=>$data]);
                }
            }
        }
        usleep(500);
        $db->reconnect();
//        $process->checkProcessTime(true);
    }
}catch (DBException $e){
    if(!empty($dataStr)){
        $queue->push($dataStr,1,"right");
    }
    $process->log($e->getMessage());
    $process->restartProcess();
}catch (Exception $e){
    Tools::writeLog(["key"=>"cover","msg"=>"封面截图失败【{$e->getMessage()}】","detail"=>$data]);
}